package com.ycy.dynamic;

import com.ycy.dynamic.f.*;
import com.ycy.util.JsonUtil;
import org.flowable.common.engine.api.FlowableException;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.engine.impl.cmd.AbstractDynamicInjectionCmd;
import org.flowable.bpmn.BpmnAutoLayout;
import org.flowable.bpmn.model.*;
import org.flowable.bpmn.model.Process;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.dynamic.BaseDynamicSubProcessInjectUtil;
import org.flowable.engine.impl.dynamic.DynamicUserTaskBuilder;
import org.flowable.engine.impl.persistence.entity.DeploymentEntity;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.task.service.TaskService;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;

import java.util.*;


public class AfterSignUserTaskCmd extends AbstractDynamicInjectionCmd implements Command<Void> {
  //流程实例id
  protected String processInstanceId;

//  后加签的节点信息
  private DynamicUserTaskBuilder signUserTaskBuilder;

  //当前流程节点的id
  private String taskId;

  public AfterSignUserTaskCmd(DynamicUserTaskBuilder signUserTaskBuilder,String taskId, String processInstanceId) {
    this.signUserTaskBuilder = signUserTaskBuilder;
    this.taskId = taskId;
    this.processInstanceId = processInstanceId;
  }

  @Override
  public Void execute(CommandContext commandContext) {
    createDerivedProcessDefinitionForProcessInstance(commandContext, processInstanceId);
    return null;
  }

  @Override
  protected void updateBpmnProcess(CommandContext commandContext, Process process,
                                   BpmnModel bpmnModel, ProcessDefinitionEntity originalProcessDefinitionEntity, DeploymentEntity newDeploymentEntity) {

    //找到当前节点的实体
    TaskService taskService = CommandContextUtil.getTaskService(commandContext);
    TaskEntity taskEntity = taskService.getTask(taskId);
    if (taskEntity == null) {
      throw new FlowableObjectNotFoundException("task:" + taskId + " not found");
    }
    //查找当前节点对应的执行执行实体（感觉兴趣的可以搜下流程执行的实例信息 表为ACT_RU_EXECUTION）
    ExecutionEntity currentExecutionEntity = CommandContextUtil.getExecutionEntityManager(commandContext).findById(taskEntity.getExecutionId());
    if (currentExecutionEntity == null) {
      throw new FlowableObjectNotFoundException("task:" + taskId + ",execution:" + taskEntity.getExecutionId() + " not found");
    }
    //获取当前执行节点
    String activityId = currentExecutionEntity.getActivityId();
    FlowElement flowElement = process.getFlowElement(activityId, true);
    if (!(flowElement instanceof Task)) {
      throw new FlowableException("task type error");
    }
    Activity curActivity = (Activity) flowElement;
    //由于是后加签所以需要获取当前流程节点流出的sequence
    SequenceFlow currentTaskOutSequenceFlow = curActivity.getOutgoingFlows().get(0);

    //流程的id 可以在调用的时候传入 也可以根据flwoable提供的方法生成
    String id = "rdfa-usertask-" + UUID.randomUUID().toString().replaceAll("-", "");

    //定义新的节点
    UserTask addUserTask = new UserTask();
    addUserTask.setId(id);
    addUserTask.setName("动态新增人员审批节点");
    addUserTask.setAssignee("111");

    MultiInstanceLoopCharacteristics loopCharacteristics = new MultiInstanceLoopCharacteristics();
    loopCharacteristics.setSequential(false);
    loopCharacteristics.setInputDataItem("ASSIGNEE_" + addUserTask.getId() + "_LIST");
    loopCharacteristics.setElementVariable("ASSIGNEE_" + addUserTask.getId() + "_ID");
    //支持多签或签 TODO
    loopCharacteristics.setCompletionCondition(CompletionConditionEnum.byType(1).getCompletionCondition());
    RdfaBpExpressionAccountIds expressionAccountIds = new RdfaBpExpressionAccountIds();
    //指定成员
    RdfaBpExpressionInfo expressionInfo = new RdfaBpExpressionInfo();
    expressionInfo.setType(BpConstants.EXPRESSION_TYPE_SPECIFIED_ACCOUNT_IDS);
    Set<Long> validAssigneeValueSet = new HashSet<>();
    //TODO
    validAssigneeValueSet.add(1L);
    expressionAccountIds.setAccountIds(validAssigneeValueSet);
    expressionInfo.setValue(JsonUtil.objToString(expressionAccountIds));
    RdfaBpDocumentation bpDocumentation = new RdfaBpDocumentation();
    bpDocumentation.setExpressionInfo(expressionInfo);
    addUserTask.setDocumentation(JsonUtil.objToString(bpDocumentation));
    addUserTask.setLoopCharacteristics(loopCharacteristics);
    process.addFlowElement(addUserTask);

    //定义新的sequenceFlow 将节点的source改为新的节点 taget 改为当前节点的target
    String flowId = "sequenceFlow_" + CommandContextUtil.getProcessEngineConfiguration(commandContext).getIdGenerator().getNextId();
    SequenceFlow newOutGoingSequenceFlow = this.createSequenceFlow(addUserTask.getId(), currentTaskOutSequenceFlow.getTargetFlowElement().getId());
    newOutGoingSequenceFlow.setId(flowId);
    process.addFlowElement(newOutGoingSequenceFlow);

    curActivity.setOutgoingFlows(Collections.singletonList(newOutGoingSequenceFlow));
    //修改原有sequenceFlow的target改为新的节点
    currentTaskOutSequenceFlow.setTargetFlowElement(addUserTask);
    currentTaskOutSequenceFlow.setTargetRef(addUserTask.getId());

    //clean清除原有的一些图的坐标信息
    bpmnModel.getLocationMap().clear();
    bpmnModel.getFlowLocationMap().clear();
    bpmnModel.getLabelLocationMap().clear();

    //重新生成图
    new BpmnAutoLayout(bpmnModel).execute();

    //当前流程的重新定义
    BaseDynamicSubProcessInjectUtil.processFlowElements(commandContext, process, bpmnModel, originalProcessDefinitionEntity, newDeploymentEntity);
  }

  @Override
  protected void updateExecutions(CommandContext commandContext, ProcessDefinitionEntity processDefinitionEntity,
                                  ExecutionEntity processInstance, List<ExecutionEntity> childExecutions) {
  }

  /**
   * 创建一个新的sequenceFlow
   */
  public SequenceFlow createSequenceFlow(String from, String to) {
    SequenceFlow flow = new SequenceFlow();
    flow.setSourceRef(from);
    flow.setTargetRef(to);
    return flow;
  }

}
